package com.xy.shop.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xy.shop.common.constant.RedisConstants;
import com.xy.shop.common.utils.EncryptUtil;
import com.xy.shop.common.utils.WebUtil;
import com.xy.shop.system.entity.User;
import com.xy.shop.web.controller.BaseController;
import com.xy.shop.web.entity.ApplyOrder;
import com.xy.shop.web.entity.WxUser;
import com.xy.shop.web.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController{

	@Value("${weixin.appid}")
	private  String wxAppId;
	@Value("${weixin.appSecret}")
	private  String vxSecret;
	@Value("${weixin.redirecturi}")
	private  String vxRedirecturi;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@RequestMapping(value = "/login" , method = RequestMethod.GET)
	public String login(ModelMap model) {
		return "admin/login";
	}
	@Resource
	private WebUtil webUtil;
	@Resource
	private WxUserService tWxUserService;

	@Resource
	private ApplyOrderService applyOrderService;

	/**
	 * 用户登录验证
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
						@RequestParam(value = "rememberMe",defaultValue = "false") Boolean rememberMe,
						ModelMap model) {
		try {
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			token.setRememberMe(rememberMe);
			subject.login(token);
			 return redirect("/admin/index");
			// return redirect("/admin/gameList");
		} catch (AuthenticationException e) {
			model.put("message", e.getMessage());
		}
		return "admin/login";
	}


	@RequestMapping(value = "/logout" , method = RequestMethod.GET)
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return redirect("admin/login");
	}

	@RequestMapping(value ={"/index"}, method = RequestMethod.GET)
	public String index(@RequestParam( value = "appId", required = false, defaultValue = "0") String appId,Model model){
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		/*if (Integer.valueOf(appId) > 0) {
			UserApp userApp=userAppService.selectByPrimaryKey(user.getId(),Integer.valueOf(appId));
			if (Objects.isNull(userApp)) {
				return redirect("/admin/gameList");
			}
		}
		if (user != null) {
			DimApp dimApp=dimAppService.selectByPrimaryKey(Integer.valueOf(appId));
			if (dimApp != null){
				redisTemplate.opsForValue().set(WebConstants.RedisKeyPrefix.APPID+user.getLoginName(),dimApp.getAppId()+","+dimApp.getAppCode()+","+dimApp.getAppName(),1,TimeUnit.DAYS);
				model.addAttribute("systemName",dimApp.getAppName());
			}
		}*/
        return "admin/index";
	}

	@ResponseBody
    @RequestMapping(value ={"/indexChart"}, method = RequestMethod.POST)
	public Object indexChart(){
		Map<String,Object> result = new HashMap<>();
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		String redisData = redisTemplate.opsForValue().get(RedisConstants.INDEX_DATA_CACHE+webUtil.getAppId(user.getLoginName()));
		//首页Chart数据
		if(redisData == null){/*
			Map<String,Object> param = new HashMap<>();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			param.put("etime",sf.format(calendar.getTime()));
			calendar.add(Calendar.DATE,-6);
			param.put("stime",sf.format(calendar.getTime()));
			getAppParams(param);
			List<Map<String, Object>> roomList = factDayRoomsService.selectChart(param);
			List<Map<String, Object>> dauList = factDayDauService.selectChart(param);
			List<Map<String, Object>> registerList = factDayRegisterUserService.selectChart(param);
			calendar.add(Calendar.DATE,5);
			param.put("stime",sf.format(calendar.getTime()));
			param.put("etime",sf.format(calendar.getTime()));
			List<Map<String,Object>> clubRoomList = factDayClubRoomsService.selectChart(param);
			param.put("yestodayDate",sf.format(calendar.getTime()));
			calendar.add(Calendar.DATE,1);
			param.put("todayDate",sf.format(calendar.getTime()));
			List<Map<String, Object>> playList = factDayPlayRoomsService.selectChartForIndex(param);
			result.put("room",getChartResult(roomList));
			result.put("clubRoom",getChartResult(clubRoomList));
			result.put("dau",getChartResult(dauList));
			result.put("register",getChartResult(registerList));
			result.put("play",getPlayChartResult(playList));
			redisTemplate.opsForValue().set(RedisConstants.INDEX_DATA_CACHE+webUtil.getAppId(user.getLoginName()),JSONObject.toJSONString(result),10,TimeUnit.SECONDS);
		*/}else {
			Map map = JSONObject.parseObject(redisData, Map.class);
			result = (Map<String,Object>)map;
		}
        return result;
	}

	/**
	 * 带参重定向
	 *
	 * @param path
	 * @return
	 */
	private String redirect(String path) {
		return "redirect:" + path;
	}

	private JSONArray getChartResult(List<Map<String,Object>> list){
        JSONArray jsonArray = new JSONArray();

            List<String> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            for (Map map : list) {
                list1.add(map.get("x").toString());
                list2.add(Integer.valueOf(map.get("y").toString()));
            }
            jsonArray.add(list1);
            jsonArray.add(list2);
        return jsonArray;
    }

	private JSONArray getPlayChartResult(List<Map<String,Object>> list){
		JSONArray jsonArray = new JSONArray();
		List<String> list1 = new ArrayList<>();
		List<Integer> list2 = new ArrayList<>();
		List<Integer> list3 = new ArrayList<>();
		for (Map map : list) {
			list1.add(map.get("play_name").toString());
			list2.add(Integer.valueOf(map.get("lastday_rooms").toString()));
			list3.add(Integer.valueOf(map.get("today_rooms").toString()));
		}
		jsonArray.add(list1);
		jsonArray.add(list2);
		jsonArray.add(list3);
		return jsonArray;
	}

	/**微信登录*/
	@ResponseBody
	@RequestMapping(value = "/wxlogin" , method = RequestMethod.GET)
	public Map wxlogin(ModelMap model) {
		Map<String,Object> map=new HashMap<>();

		/**微信登录地址*/
		String url=SnsAPI.connectOauth2Authorize(wxAppId, vxRedirecturi,true, "state");
		model.addAttribute("url", url);
		map.put("success",true);
		map.put("url",url);
		return map;
	}

	/**
	 * 微信回调接口
	 * */
	@RequestMapping(value = "/wxLoginNotify" , method = RequestMethod.GET)
	public String wxLoginNotify(HttpServletRequest request, Model model ) {
		String code=request.getParameter("code");
		logger.debug("agent wx login ================ code:"+code);

		SnsToken snsToken=SnsAPI.oauth2AccessToken(wxAppId, vxSecret,code);
		weixin.popular.bean.user.User user1=SnsAPI.userinfo(snsToken.getAccess_token(), snsToken.getOpenid(),"zh_CN");
		//				String accountName="ogl_xwv2CcSdAFbgMptWiuZ3X9yg";//"ogl_xwv4KKiJuyb0mAdK0OFzlBBQ";
		logger.debug("agent wx login ================ user::::>>>>{openid:"+user1.getOpenid()+",unionid:"+user1.getUnionid()+"}");
		//这里取unionid
		WxUser tWxUser ;
		if (Objects.nonNull(user1)) {
			tWxUser= tWxUserService.selectByOpendId(user1.getOpenid());
			if(Objects.isNull(tWxUser)) {
				tWxUser=new WxUser();
				tWxUser.setIcon(user1.getHeadimgurl());
				tWxUser.setSex(user1.getSex());
				tWxUser.setOpenId(user1.getOpenid());
				tWxUser.setName(user1.getNickname());
				int count=tWxUserService.updateByPrimaryKeySelective(tWxUser);
			}
		}else{
			return redirect("/static/html/login.html");
		}

		/**参数加密*/
		/**参数加密说明:
		 * 			随机字符串无效(前五位)，后部分参数为加密后参数，解密时前五位不参与解密
		 * 			*/
		String params=EncryptUtil.randomStr(5);
		if(Objects.nonNull(tWxUser)) {
			String data= +tWxUser.getUid()+"@"+tWxUser.getOpenId();
			try {
				params +=	EncryptUtil.encrypt(data);
			} catch (Throwable throwable) {
				throwable.printStackTrace();
			}
		}
		return redirect("/static/html/order_writer.html?p="+params);
	}

	/**
	 * 申请订单提交
	 * */
	@ResponseBody
	@RequestMapping(value = "/applyOrder" , method = RequestMethod.POST)
	public Map<String, Object> applyOrder(HttpServletRequest request , ApplyOrder applyOrder) {
		Map<String, Object> result=applyOrderService.order(applyOrder);
		return result;
	}
}
